//
//  TYHLoginController.m
//  OpenPractice
//
//  Created by tanyuehong on 16/3/6.
//  Copyright © 2016年  lijinghua. All rights reserved.
//

#import "UIDevice+Info.h"
#import "HyLoginButton.h"
#import "TYHUIDifine.h"
#import "OPLoginTextField.h"
#import "CHRPhoneNumberMask.h"
#import "TYHLoginController.h"
#import "UIView+GaussianBlur.h"
#import "CHRTextFieldFormatter.h"
#import "TYHSMSVerifyController.h"
#import "TYHPassWdViewController.h"
#import "UIButton+backgroundColorForState.h"


#define  USERPWDLENGTH  6
#define  USERPHONELENGTH  13
#define  INPUT_TEXTFILED_WIDTH  250


@interface TYHLoginController () <UITextFieldDelegate>

@property (nonatomic, strong) UIButton *backBtn;         // 返回button
@property (nonatomic, strong) HyLoginButton *loginBtn;   // 登陆button

@property (nonatomic, strong) LoginPhoneTextField *phoneTextField;   // 手机号码
@property (nonatomic, strong) LoginPasswordTextField *pswTextField;  // 密码

@property (nonatomic, strong) CHRTextFieldFormatter *phoneNumberFormatter;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicatorView;
@property (nonatomic, strong) UIView *alertConfirm;
@property (nonatomic, weak) UILabel *alertphoneNum;
@property (nonatomic, copy) NSString *phoneNum;

@end

@implementation TYHLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCloseBtn];
    [self initViews];
    
    [self.view setBackgroundColor:[UIColor colorWithHex:0xffffff]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledTextChange:) name:UITextFieldTextDidChangeNotification object:nil];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewDidClick)];
    [self.view addGestureRecognizer:tap];
}

- (void)viewDidClick {
    [self.phoneTextField resignFirstResponder];
    [self.pswTextField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    [self.phoneTextField resignFirstResponder];
    [self.pswTextField resignFirstResponder];
    return YES;
}

- (void)textFiledTextChange:(NSNotification *)no {
    UITextField *textFile = no.object;
    if (self.phoneTextField == textFile || self.pswTextField == textFile) {
        if (self.phoneTextField.text.length == USERPHONELENGTH && self.pswTextField.text.length >= USERPWDLENGTH ) {
            [self setButtonEnable:YES];
        } else if (self.phoneTextField == textFile && self.phoneTextField.text.length>USERPHONELENGTH){
            self.phoneTextField.text = [self.phoneTextField.text substringToIndex:USERPHONELENGTH];
        } else {
            [self setButtonEnable:NO];
        }
    }
}

- (void)setButtonEnable:(BOOL)enable {
    self.loginBtn.enabled = enable;
    self.loginBtn.backgroundColor = enable ? kThemeGreenColor : [UIColor colorWithHex:0x4cc760 andAlpha:0.5];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.phoneTextField becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.phoneTextField resignFirstResponder];
    if (self.phoneNum.length == USERPHONELENGTH) {
        self.loginBtn.hidden = NO;
    }
    [super viewWillDisappear:animated];
}

#pragma mark - Private

- (void)initCloseBtn {
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(7, kZDStatusBarHeight+8, 42, 42)];
    [backBtn setImage:[UIImage imageNamed:@"login_close_btn"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    self.backBtn = backBtn;
}

- (void)setUpSubViews {
    UIImageView *girlIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"register_girlIcon.png"]];
    girlIcon.size = CGSizeMake(110, 140);
    girlIcon.center = CGPointMake(self.view.center.x, 70);
}

- (void)initViews {
    UILabel *guideLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, self.backBtn.bottom+12, kScreenWidth - 80, 26)];
    guideLabel.font = [UIFont boldSystemFontOfSize:22];
    guideLabel.textColor = [UIColor colorWithHex:0x333333];
    guideLabel.text = @"欢迎加入开源实践网";
    [self.view addSubview:guideLabel];

    
    self.phoneTextField = [[LoginPhoneTextField alloc] initWithPhone:[[TYHLoginManager sharedInstance] getUserTryLoginPhoneNum]];
    self.phoneTextField.delegate = self;
    [self.view addSubview:self.phoneTextField];
    
    self.pswTextField = [[LoginPasswordTextField alloc] initWithText:@"" placeholder:@"请输入密码"];
    self.pswTextField.delegate = self;
    [self.view addSubview:self.pswTextField];
    
    [self.phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(guideLabel.mas_bottom).offset(47.5);
        make.left.right.inset(33);
        make.height.equalTo(@44);
    }];
    [self.pswTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneTextField.mas_bottom).offset(12);
        make.left.right.height.equalTo(self.phoneTextField);
    }];
    

    self.phoneNumberFormatter = [[CHRTextFieldFormatter alloc] initWithTextField:self.phoneTextField mask:[CHRPhoneNumberMask new]];
//    HyLoginButton *loginButton = [[HyLoginButton alloc] initWithFrame:CGRectMake(40, lineView.bottom + 30, kScreenWidth - 80, 40)];
    
    
    HyLoginButton *loginButton = [[HyLoginButton alloc] initWithFrame:CGRectZero];
    [loginButton setTitle:@"登陆" forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(nexBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.loginBtn = loginButton;
    [self setButtonEnable:NO];
    self.loginBtn.titleLabel.textColor = [UIColor whiteColor];
    self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    self.loginBtn.layer.cornerRadius = 15.f;
    [self.view addSubview:loginButton];
    
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(40);
        make.top.equalTo(self.pswTextField.mas_bottom).offset(40);
        make.right.equalTo(self.view).offset(-40);
        make.height.mas_equalTo(40);
    }];
}

- (void)backBtnClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)nexBtnClick:(UIButton *)next {
    NSString *userPhone = [self.phoneTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *userPwd =self.pswTextField.text;
    if (!userPhone) {
        return ;
    }
    [self.pswTextField resignFirstResponder];
    [self.phoneTextField resignFirstResponder];
   
    [[TYHLoginManager sharedInstance] loginWithPhoneNum:userPhone passWd:userPwd compeletBlock:^(NSError *error, id resultObject) {
        [self.loginBtn succeedAnimationStop];
        if(error) {
          
        } else {
            [self backBtnClick];
        }
    }];
   
}


- (void)checkPhoneStatusEndWithError:(NSError *)error result:(id)result {
    if (error) {
        [self setButtonEnable:YES];
    } else {
        if (result && [result isKindOfClass:[NSDictionary class]]) {
            NSInteger type = [[result objectForKey:@"phoneType"]
                               integerValue];
            NSString *phoneNum = [result objectForKey:@"phoneNum"];
            [[TYHLoginManager sharedInstance] setUserTryLoginPhoneNum:phoneNum];
            if (type == 1) {
                [self goToPassWdLoginController:phoneNum];
            }
            if (type ==2) {
                self.phoneNum = phoneNum;
                [self.view.window addSubview:self.alertConfirm];
            }
            if (type == 3) {
                [self gotoSetPasswdController:phoneNum];
            }
        } else {
            [self.loginBtn failedAnimationWithCompletion:nil];
        }
        [self setButtonEnable:YES];
    }
}

- (void)goToPassWdLoginController:(NSString *)phone {
    TYHPassWdViewController *passWdVc = [[TYHPassWdViewController alloc] init];
    passWdVc.phoneNum = phone;
    [self.navigationController pushViewController:passWdVc animated:YES];
}

- (void)gotoSetPasswdController:(NSString *)phone {
    TYHSMSVerifyController *setPassWdVc = [[TYHSMSVerifyController alloc] init];
    setPassWdVc.phoneNum = phone;
    setPassWdVc.type = SMSVerifyCodeLoginNeedSetPW;
    [self.navigationController pushViewController:setPassWdVc animated:YES];
}

#pragma mark - Actions


- (void)backButtonTouched {
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIView *)alertConfirm {
    if (!_alertConfirm) {
        _alertConfirm = [UIView GaussianBlurViewWithDark:YES];
         CGFloat alertWidth = kScreenWidth-(DeviceIsPad?200:([UIDevice isIPhone6Plus]?100:30));
        UIView *alert = [[UIView alloc] initWithFrame:CGRectMake(0, 0, alertWidth, 201)];
        alert.layer.masksToBounds = YES;
        alert.layer.cornerRadius = 10;
        
        UIButton *cancel = [[UIButton alloc] initWithFrame:CGRectMake(15, 140, 128, 40)];
        cancel.layer.cornerRadius = 5;
        cancel.layer.masksToBounds = YES;
        cancel.layer.borderWidth = 1 / [UIScreen mainScreen].scale;
        cancel.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        [cancel setBackgroundColor:[UIColor whiteColor]  forState:UIControlStateNormal];
        [cancel setBackgroundColor:[UIColor colorWithHex:0xbbbbbb]  forState:UIControlStateHighlighted];
        cancel.titleLabel.font = [UIFont systemFontOfSize:18];
        [cancel setTitleColor:kTYH666666TextColor forState:UIControlStateNormal];
        [cancel setTitle:@"取消" forState:UIControlStateNormal];
        [cancel addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *okBtn = [[UIButton alloc] initWithFrame:CGRectMake(158, 140, 128, 40)];
        okBtn.layer.borderWidth = 1 / [UIScreen mainScreen].scale;
        okBtn.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        okBtn.layer.cornerRadius = 5;
        okBtn.layer.masksToBounds = YES;
        [okBtn setBackgroundColor:kThemeGreenColor forState:UIControlStateNormal];
        [okBtn setBackgroundColor:kThemeGreenTranslucentColor  forState:UIControlStateHighlighted];
        okBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        [okBtn setTitle:@"确定" forState:UIControlStateNormal];
        [okBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [okBtn addTarget:self action:@selector(confirmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        
        UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(90, 28, alertWidth-180, 24)];
        titleLable.text = @"验证手机号码";
        titleLable.textColor = [UIColor blackColor];
        titleLable.font = [UIFont systemFontOfSize:20.0];
        
        UILabel *decLabel = [[UILabel alloc] initWithFrame:CGRectMake(38, 62, alertWidth-76, 18)];
        decLabel.font = [UIFont systemFontOfSize:15];
        decLabel.textColor = kTYH333333TextColor;
        decLabel.text = @"我们将发送验证码短信到这个号码";
       
        UILabel *phoneNum = [[UILabel alloc] initWithFrame:CGRectMake(73, 88, alertWidth-146, 27)];
        phoneNum.font = [UIFont systemFontOfSize:22.0];
        phoneNum.textColor = [UIColor blackColor];
       
        [alert addSubview:titleLable];
        [alert addSubview:decLabel];
        [alert addSubview:phoneNum];
        [alert addSubview:cancel];
        [alert addSubview:okBtn];
        alert.backgroundColor = [UIColor whiteColor];
        [_alertConfirm addSubview:alert];
        alert.center = _alertConfirm.center;
        self.alertphoneNum = phoneNum;
    }
    self.alertphoneNum.text = [NSMutableString stringWithString:self.phoneTextField.text];
    return _alertConfirm;
}

- (void)confirmBtnClick:(UIButton *)btn {
    [self.alertConfirm removeFromSuperview];
    [self.phoneTextField becomeFirstResponder];
    TYHSMSVerifyController *smsVc = [[TYHSMSVerifyController alloc] init];
    smsVc.type = SMSVerifyREGISTERTYPE;
    smsVc.phoneNum = self.phoneNum;
    [self.navigationController pushViewController:smsVc animated:YES];
}

- (void)cancelBtnClick:(UIButton *)btn {
    [self.alertConfirm removeFromSuperview];
    [self.phoneTextField becomeFirstResponder];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.phoneTextField) {
        return [self.phoneNumberFormatter textField:textField shouldChangeCharactersInRange:range replacementString:string];
    } else {
        return YES;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIButton *)addOtherLoginButton:(NSString *)title selector:(SEL)selector {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:kTYH333333TextColor forState:UIControlStateNormal];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    return button;
}


@end
